<template>
    <el-dialog
        title="弹窗设置"
        width="580px"
        custom-class="confirm-add-dialog"
        :visible.sync="show"
    >
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            :rules="formRule"
            label-width="80px"
        >
            <!-- 赞助商设置 -->
            <el-form-item
                class="task-form-item"
                size="small"
                prop="image_url"
                label="上传图片:"
            >

                <el-upload
                    :show-file-list="false"
                    :http-request="e=> {fnUploadImageOfCustomerLogo(e)}"
                    accept="image/*"
                    class="upload-demo"
                    drag
                    action="https://jsonplaceholder.typicode.com/posts/"
                >
                    <img
                        v-if="formData.image_url"
                        :src="formData.image_url"
                        class="avatar"
                    >
                    <i
                        class="el-icon-upload"
                        v-if="!formData.image_url"
                    />
                    <div
                        class="el-upload__text"
                        v-if="!formData.image_url"
                    >将文件拖到此处，或<em>点击上传</em></div>
                    <!-- <div
                            class="el-upload__tip"
                            slot="tip"
                        >只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>
                <span style="display:inline-block;color:#999;margin-left:12px">*只能上传jpg/png文件</span>
            </el-form-item>
            <el-form-item
                class="task-form-item"
                size="small"
                prop="button-title"
                label="按钮"
            >
                <el-input
                    placeholder="请填写按钮名称"
                    v-model="formData.button_title"
                    size="small"
                    class="task-input"
                />
            </el-form-item>

            <el-form-item
                class="task-form-item"
                size="small"
                label="链接:"
            >
                <el-input
                    placeholder="按钮链接"
                    v-model="formData.jump_url"
                    size="small"
                    class="task-input"
                />
                <span style="display:inline-block;color:#999;margin-left:12px">*如需跳转, 请联系开发人员索取链接</span>
            </el-form-item>

            <el-form-item
                class="task-form-item"
                size="small"
                prop="showTime"
                label="弹窗周期:"
            >
                <el-date-picker
                    v-model="formData.showTime"
                    type="datetimerange"
                    range-separator="至"
                    size="small"
                    class="task-input"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                />
            </el-form-item>

            <div class="operate-baar">
                <el-button
                    size="medium"
                    type="primary"
                    @click="fnSubmit()"
                >提交</el-button>
            </div>
        </el-form>
    </el-dialog>
</template>

<script>
export default {
    ecomponents: {},
    data() {
        var validateLinkUrl = (rule, val, callback) => {

            if (val.indexOf('http://') != 0 && val.indexOf('https://') != 0 && val.indexOf('/page') != 0) {
                callback(new Error(rule.message));
                return;
            }
            callback();
        };

        // 验证二位数组,且数组内元素不为空
        var validateArray = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error(rule.message));
                    return;
                }
                callback();
            }
        };

        return {
            show: false,
            popup_no: '',
            formData: {
                button_title: "",
                image_url: '',
                jump_url: '',
                scope: [],
                start_time: 0,
                end_time: 0,
                showTime: [this.fnInitTimeNow(), ''],
                status: 0
            },
            formRule: {
                jump_url: [
                    { validator: validateLinkUrl, message: '请填写正确的链接', trigger: 'blur' }
                ],
                image_url: [
                    { required: true, message: '请上传图片', trigger: 'change' }
                ],
                button_title: [
                    { required: true, message: '按钮名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字', trigger: 'blur' }
                ],
                showTime: [
                    { required: true, message: '请填写展示时间', trigger: 'blur' },
                    { validator: validateArray, message: '请填写正确的时间', trigger: 'blur' }
                ],
            },
            submitting: false,
            init: false,
        };
    },
    methods: {
        fnShow(data) {
            this.submitting = false;
            if (data) {
                this.formData = Object.assign({
                    showTime: [new Date(resp.data.start_time * 1000), new Date(resp.data.end_time * 1000)]
                }, data);
            }else{
                this.formData = {
                    button_title: "",
                    image_url: '',
                    jump_url: '',
                    scope: [],
                    start_time: 0,
                    end_time: 0,
                    showTime: [this.fnInitTimeNow(), ''],
                    status: 0
                };
            }
            this.init = true;
            this.show = true;
        },
        fnInitTimeNow() {
            var timestamp = new Date().getTime();

            return timestamp;
        },
        fnSubmit() {
            if (this.submitting) {
                return;
            }
            this.$refs.mainform.validate(valid => {
                if (valid) {
                    this.submitting = true;

                    let data = {
                        popup_no: this.popup_no ? this.popup_no : '',
                        button_title: this.formData.button_title,
                        image_url: this.formData.image_url,
                        jump_url: this.formData.jump_url,
                        start_time: Date.parse(this.formData.showTime[0]) / 1000,
                        end_time: Date.parse(this.formData.showTime[1]) / 1000
                    };


                    // TODO 添加地址
                    this.$post('', data, resp => {
                        if (resp.code == 1) {
                            this.$emit('submit');
                            this.show = false;
                            this.$message({
                                type: 'success',
                                center: true,
                                message: '修改成功'
                            });
                        } else {
                            this.$message({
                                type: 'warning',
                                center: true,
                                message: resp.msg
                            });
                        }
                        this.submitting = false;
                    });

                }
            });
        },
        /** 数组中删除某个元素 */
        fndeleteItem(list, index, bind) {
            list.splice(index, 1);
            this[bind] = list.length;
        },
        /** 上传组件回调 文件队列修改 */
        fnUploadChange(file, item) {
            item.preview_url = file.url;
        },
        fnBeforeUpload(file, item) {
            item.status = 'uploading';
        },
        /** 上传组件回调 上传成功 */
        fnUploadSuccess(resp, file, item) {
            item.img_url = resp.url;
            item.status = 'success';
        },
        fnUploadError(item) {
            item.preview_url = '';
            item.status = 'fail';
        },
        fnUpload(e, item) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            item.uploadTime = timeTmp;
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if (item.uploadTime != timeTmp) {
                        return;
                    }
                    if (resp.code == 1) {
                        // 调用组件成功回调,修改样式
                        e.onSuccess(resp.data, {
                            url: resp.data.url
                        }, this.fileList);
                    } else {
                        // 失败后调用组件error回调,删除对应元素
                        e.onError(resp.msg);
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                    }
                }
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnUploadImageOfCustomerLogo(e) {
            this.fnUploadImage(e, (resp) => {
                this.formData.image_url = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnReset() {
            this.$refs.mainform.resetFields();
        }
    },
};
</script>

<style lang="less" scoped>
  .avatar {
    width: 100%;
    height: 100%;
  }
  .margin-top {
    margin-top: 15px;
  }
  .banner-add-wrap {
    background: #fff;
    margin: 15px;
    margin-bottom: 0;
    padding: 30px;
    overflow: auto;
  }
  .form-unit {
    margin-bottom: 40px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .form-title {
    font-size: 16px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
    line-height: 18px;
    padding: 0 10px;
    border-left: 2px solid #1890ff;
    margin-bottom: 20px;
  }
  .task-input {
    width: 100% !important;
  }
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"] {
    -moz-appearance: textfield;
  }

  .operate-baar {
    width: 100%;
    text-align: center;
    margin-top: 20px;
  }
</style>
<style lang="less">
  .confirm-add-dialog {
    .el-dialog__body {
      padding: 20px 40px;
    }
    .el-date-editor .el-range-separator {
      width: 24px;
    }
  }
</style>